﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BizzCommInterfaces;
using System.Windows.Forms;
using System.IO;
using System.Xml;

namespace XMLTrays
{
    public class XMLInbox : Tray, IInbox
    {
        //private const string _name = "XMLInboxProvider";
        private const char _separator = ';';
        
        public string folder { get; set; }
        private string lastFile { get; set; }
        //private string concreteInboxName;

        public XMLInbox()
        {
          
            lastFile = null;
            folder = null;
            base._name = "XMLInboxProvider";
        }

        


        #region IInbox Members

        public void getConfigurationWindow()
        {

            XMLInboxConfigControl configControl = new XMLInboxConfigControl(this);
            configControl.ShowDialog();
        }

        public int getCount()
        {
            var files = Directory.GetFiles(folder).Where(name => name.EndsWith(".xml"));
            return files.Count();
        }

        public void markAsRead()
        {
          
                File.Delete(lastFile);
                lastFile = null;
           
            
        }

        //BRAND NEW ----------------------------------------------------------------------------------
        public string getWorkingMessage()
        {
            string workingMsg = null;
            var files = from f in Directory.GetFiles(folder).Where(name => name.EndsWith(".xml"))
                        orderby f ascending
                        select f;

            if (files != null)
            {
                lastFile = files.First();
                workingMsg = lastFile;
            }
            return workingMsg;
        }
        //END BRAND NEW ----------------------------------------------------------------------------------

        public BizzMessage readMessage(string messageToRead)
        {
            BizzMessage msg = null;
            if (messageToRead != null)
            {
                msg = readXMLFile(lastFile);
            }
            return msg;
        }

        /***public BizzMessage readMessage()
        {
            BizzMessage msg = null;
            var files = from f in Directory.GetFiles(folder).Where(name => name.EndsWith(".xml"))
                        orderby f ascending
                        select f;

            if (files != null)
            {
                lastFile = files.First();
                msg = readXMLFile(lastFile);

            }
            return msg;
            
            
        }*/

        public string codeMe()
        {
            string ret = folder + _separator + lastFile + _separator + _concreteName;
            return ret;
        }

        public void decodeMe(string box)
        {
            string[] attr = box.Split(_separator);
            folder = attr[0];
            lastFile = attr[1];
            _concreteName = attr[2];
        }

        #endregion

        private BizzMessage readXMLFile(string fileName)
        {
            BizzMessage msg = new BizzMessage();
            XmlDocument docLeer = new XmlDocument();
            docLeer.Load(fileName);

            
            
            XmlNodeList nodes = docLeer.SelectNodes("/mensaje");

            XmlNode node = nodes.Item(0);
            msg.Title = node.Attributes["titulo"].Value;
            msg.Attributes = new List<MsgAttribute>();
            foreach (XmlNode child in node.ChildNodes.Item(0).ChildNodes)
            {
                MsgAttribute attrib = new MsgAttribute()
                {
                    Name = child.Attributes["nombre"].Value,
                    Value = child.Attributes["valor"].Value
                };
                /*switch (child.Attributes["tipo"].Value)
                {
                    case "Texto": attrib.Type = BizzCommInterfaces.Type.text; break;
                    case "Booleano": attrib.Type = BizzCommInterfaces.Type.boolean; break;
                    case "Numero": attrib.Type = BizzCommInterfaces.Type.number; break;
                    case "Fecha": attrib.Type = BizzCommInterfaces.Type.date; break;
                }*/
                attrib.Type = msg.getMsgType(child.Attributes["tipo"].Value);
                msg.Attributes.Add(attrib);
                
            }

            
            
            
            return msg;
        }


        public string getInboxName()
        {
            return _name;
        }

        public string[] getDescription()
        {
            string[] ret = new string[9];
            ret[0] = "Cada mensaje será un archivo XML con el siguiente formato:";
            ret[1] = "";
            ret[2] = "\"<mensaje titulo=\"este es el titulo del mensaje\">";
            ret[3] = "<atributos>   ";
            ret[4] = "<atributo nombre=\"Apellido\" tipo=\"Texto\" valor=\"Perez\"/> ";
            ret[5] = "<atributo nombre=\"Edad\" tipo=\"Numero\" valor=\"30\"/> ";
            ret[6] = "<atributo nombre=\"Casado\" tipo=\"Booleano\" valor=\"True\"/>  ";
            ret[7] = "</atributos> ";
            ret[8] = "</mensaje> ";

                
            return ret;
        }



        public bool isReady()
        {
            return (folder != null);
        }


        public string getConcreteInboxName()
        {
            return _concreteName;
        }

        public void setConcreteInboxName(string name)
        {
            _concreteName = name;
        }
    }
}
